package com.citywy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class ReturnController {

    /**
     * 使用request的转发
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("return1")
    public void getReturn1(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("使用request转发页面");
        request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
    }

    /**
     * 使用sendRedirect重定向
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("return2")
    public void getReturn2(HttpServletRequest request,HttpServletResponse response) throws Exception{
        System.out.println("通过sendRedirect重定向");
        response.sendRedirect("return1");
    }

    /**
     * 返回json字符串(异步)
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("return3")
    public void getReturn3(HttpServletRequest request,HttpServletResponse response) throws Exception{
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write("json串");
    }

    /**
     * 返回ModelAndView
     * @return
     */
    @RequestMapping("return4")
    public ModelAndView getReturn4(){
        ModelAndView res = new ModelAndView();
        //将地址直接写在new ModelAndView的带参构造中更常用
        res.setViewName("/WEB-INF/pages/mavSuccess");
        res.addObject("name","塔睿");
        res.addObject("age",19);
        return res;
    }

    /**
     * 返回String类型的forward转发和Redirect重定向
     * @return
     */
    @RequestMapping("return5")
    public String getReturn5(){
        System.out.println("这是String类型转发");
        //1.转发到页面
//        return "forward:/WEB-INF/pages/success.jsp";
        //2.转发到另一个方法(链接不变)
//        return "forward:/return4";

//        return "redirect:/return4";

        return "/WEB-INF/pages/success";
    }


}
